import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _class, _class2;

/**
 * Company - 租户级权限维护tab页 - 客户
 * @date: 2018-7-31

 */
import React from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Modal, Table, Tooltip, Switch } from 'antd';
import { Bind } from 'lodash-decorators';
import intl from 'utils/intl';
import uuidv4 from 'uuid/v4'; // import Switch from 'components/Switch';

import Lov from 'components/Lov';
import notification from 'utils/notification';
import { createPagination, tableScrollWidth } from 'utils/utils';
/**
 * 使用 Form.Item 组件
 */

var FormItem = Form.Item;
/**
 * 租户级权限管理 - 客户
 * @extends {Component} - React.Component
 * @reactProps {Object} authorityCustomer - 数据源
 * @reactProps {Object} loading - 数据加载是否完成
 * @reactProps {Object} form - 表单对象
 * @reactProps {Function} [dispatch=function(e) {return e;}] - redux dispatch方法
 * @return React.element
 */

var Customer = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = connect(function (_ref) {
  var authorityCustomer = _ref.authorityCustomer,
      loading = _ref.loading;
  return {
    authorityCustomer: authorityCustomer,
    loading: loading.models.authorityCustomer
  };
}), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec(_class = _dec2(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(Customer, _React$Component);

  var _super = _createSuper(Customer);

  /**
   *Creates an instance of Customer.
   * @param {*} props 属性
   * @memberof Customer
   */
  function Customer(props) {
    var _this;

    _classCallCheck(this, Customer);

    _this = _super.call(this, props);

    _this.handleTableChange = function (pagination) {
      var _this$props = _this.props,
          dispatch = _this$props.dispatch,
          userId = _this$props.userId;
      var formValues = _this.state.formValues;
      var params = {
        page: pagination.current - 1,
        size: _this.PageSize
      };

      var staticData = _objectSpread(_objectSpread(_objectSpread({
        userId: userId
      }, params), formValues), {}, {
        authorityTypeCode: 'CUSTOMER'
      }); // if (sorter.field) {
      //   params.sort = {
      //     name: sorter.field,
      //     order: sorter.order,
      //   };
      // }


      dispatch({
        type: 'authorityCustomer/fetch',
        payload: staticData
      });
    };

    _this.PageSize = 10;
    _this.state = {
      selectedRows: [],
      newCreateRows: [],
      formValues: {}
    };
    return _this;
  }

  _createClass(Customer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.queryValue();
    }
    /**
     *增加一行
     *
     * @memberof Customer
     */

  }, {
    key: "addData",
    value: function addData() {
      var dispatch = this.props.dispatch;
      var authorityLineId = "authorityLineId".concat(uuidv4());
      var data = {
        authorityLineId: authorityLineId,
        isCreate: true,
        isEditing: true
      };
      this.setState({
        newCreateRows: [].concat(_toConsumableArray(this.state.newCreateRows), [data])
      });
      dispatch({
        type: 'authorityCustomer/addNewData',
        payload: data
      });
    }
    /**
     *行取消事件
     *
     * @param {*} record 行数据
     * @memberof Customer
     */

  }, {
    key: "cancel",
    value: function cancel(record) {
      var dispatch = this.props.dispatch;
      var newCreateRows = this.state.newCreateRows;

      if (record.isCreate) {
        var listData = newCreateRows.filter(function (item) {
          return item.authorityLineId !== record.authorityLineId;
        });
        this.setState({
          newCreateRows: listData
        });
        dispatch({
          type: 'authorityCustomer/removeNewAdd',
          payload: {}
        });
      } else {
        this.edit(record, false);
      }
    }
    /**
     *编辑事件
     *
     * @param {*} record 行数据
     * @param {*} flag 是否编辑状态标记
     * @memberof Customer
     */

  }, {
    key: "edit",
    value: function edit(record, flag) {
      var _this$props2 = this.props,
          dispatch = _this$props2.dispatch,
          _this$props2$authorit = _this$props2.authorityCustomer.data,
          data = _this$props2$authorit === void 0 ? {} : _this$props2$authorit;
      var index = data.list.findIndex(function (item) {
        return item.authorityLineId === record.authorityLineId;
      });
      dispatch({
        type: 'authorityCustomer/editRow',
        payload: {
          data: [].concat(_toConsumableArray(data.slice(0, index)), [_objectSpread(_objectSpread({}, record), {}, {
            isEditing: flag
          })], _toConsumableArray(data.slice(index + 1)))
        }
      });
    }
    /**
     *表格选中事件
     *
     * @param {*} _ 占位
     * @param {*} rows 选中行
     * @memberof Customer
     */

  }, {
    key: "handleSelectRows",
    value: function handleSelectRows(_, rows) {
      this.setState({
        selectedRows: rows
      });
    }
    /**
     *删除方法
     *
     * @memberof Customer
     */

  }, {
    key: "remove",
    value: function remove() {
      var _this2 = this;

      var _this$props3 = this.props,
          dispatch = _this$props3.dispatch,
          userId = _this$props3.userId;
      var _this$state = this.state,
          selectedRows = _this$state.selectedRows,
          newCreateRows = _this$state.newCreateRows;

      var onOk = function onOk() {
        var deleteRows = selectedRows.filter(function (row) {
          return !row.isCreate;
        });
        var deleteCreateRows = selectedRows.filter(function (row) {
          return row.isCreate;
        });

        if (deleteCreateRows.length > 0) {
          var listData = newCreateRows.filter(function (newRow) {
            var arr = deleteCreateRows.filter(function (deleteRow) {
              return deleteRow.authorityLineId === newRow.authorityLineId;
            });
            return !(arr.length > 0);
          });

          _this2.setState({
            newCreateRows: listData
          });
        }

        if (deleteRows.length > 0) {
          dispatch({
            type: 'authorityCustomer/delete',
            payload: {
              userId: userId,
              deleteRows: deleteRows
            }
          }).then(function (response) {
            if (response) {
              _this2.refresh();

              notification.success();
            }
          });
        } else {
          _this2.refresh();

          notification.success();
        }
      };

      Modal.confirm({
        title: intl.get('cpaas.common.message.confirm.remove').d('确定删除选中数据？'),
        onOk: onOk
      });
    }
    /**
     *刷新
     *
     * @memberof Customer
     */

  }, {
    key: "refresh",
    value: function refresh() {
      var _this$props4 = this.props,
          dispatch = _this$props4.dispatch,
          userId = _this$props4.userId;
      this.setState({
        selectedRows: [],
        newCreateRows: []
      });
      var staticData = {
        userId: userId,
        page: 0,
        size: this.PageSize,
        authorityTypeCode: 'CUSTOMER'
      };
      dispatch({
        type: 'authorityCustomer/fetch',
        payload: staticData
      });
    }
    /**
     *保存数据
     *
     * @memberof Customer
     */

  }, {
    key: "dataSave",
    value: function dataSave() {
      var _this3 = this;

      var _this$props5 = this.props,
          form = _this$props5.form,
          dispatch = _this$props5.dispatch,
          _this$props5$authorit = _this$props5.authorityCustomer.head,
          head = _this$props5$authorit === void 0 ? {} : _this$props5$authorit,
          userId = _this$props5.userId;
      var newCreateRows = this.state.newCreateRows;
      form.validateFields(function (err, values) {
        if (!err) {
          var arr = [];
          var isNewRowKeys = newCreateRows.filter(function (v) {
            return v.isEditing;
          });
          var fieldsArr = ['dataName', 'dataCode', 'dataId'];
          isNewRowKeys.forEach(function (item) {
            var itemObj = {};
            fieldsArr.forEach(function (_item) {
              itemObj["".concat(_item)] = values["".concat(item.authorityLineId, "#").concat(_item)];
            });

            if (!item.isCreate) {
              itemObj.authorityLineId = item.authorityLineId;
              itemObj.objectVersionNumber = item.objectVersionNumber;
            }

            arr.push(itemObj);
          });
          dispatch({
            type: 'authorityCustomer/add',
            payload: {
              authorityTypeCode: 'CUSTOMER',
              userId: userId,
              userAuthority: head,
              userAuthorityLineList: arr
            }
          }).then(function (response) {
            if (response) {
              _this3.refresh();

              notification.success();
            }
          });
        }
      });
    }
    /**
     *查询数据
     *
     * @memberof Customer
     */

  }, {
    key: "queryValue",
    value: function queryValue() {
      var _this4 = this;

      var _this$props6 = this.props,
          form = _this$props6.form,
          dispatch = _this$props6.dispatch,
          userId = _this$props6.userId;
      var staticData = {
        userId: userId,
        page: 0,
        size: this.PageSize,
        authorityTypeCode: 'CUSTOMER'
      };
      form.validateFields(function (err, fieldsValue) {
        if (!err) {
          _this4.setState({
            formValues: fieldsValue
          });

          dispatch({
            type: 'authorityCustomer/fetch',
            payload: _objectSpread(_objectSpread({}, fieldsValue), staticData)
          });
        }
      });
    }
    /**
     *lov选中后渲染同行其他数据
     *
     * @param {*} lovRecord
     * @param {*} tableRecord
     * @memberof Customer
     */

  }, {
    key: "setDataCode",
    value: function setDataCode(lovRecord, tableRecord) {
      this.props.form.setFieldsValue(_defineProperty({}, "".concat(tableRecord.authorityLineId, "#dataCode"), lovRecord.companyNum));
      this.props.form.setFieldsValue(_defineProperty({}, "".concat(tableRecord.authorityLineId, "#dataName"), lovRecord.companyName));
    }
    /**
     *分页change事件
     *
     * @memberof Customer
     */

  }, {
    key: "includeAllFlag",
    value:
    /**
     *点击加入全部后触发事件
     *
     * @param {*} checked switch的value值
     * @memberof Customer
     */
    function includeAllFlag(checked) {
      var _this5 = this;

      var _this$props7 = this.props,
          dispatch = _this$props7.dispatch,
          userId = _this$props7.userId,
          _this$props7$authorit = _this$props7.authorityCustomer.head,
          head = _this$props7$authorit === void 0 ? {} : _this$props7$authorit;
      dispatch({
        type: 'authorityCustomer/add',
        payload: {
          authorityTypeCode: 'CUSTOMER',
          userId: userId,
          userAuthority: _objectSpread(_objectSpread({}, head), {}, {
            includeAllFlag: checked ? 1 : 0
          }),
          userAuthorityLineList: []
        }
      }).then(function (response) {
        if (response) {
          _this5.refresh();

          notification.success();
        }
      });
    }
    /**
     *渲染查询结构
     *
     * @returns
     * @memberof Customer
     */

  }, {
    key: "renderForm",
    value: function renderForm() {
      var _this6 = this;

      var getFieldDecorator = this.props.form.getFieldDecorator;
      return /*#__PURE__*/React.createElement(Form, {
        layout: "inline"
      }, /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator('dataName')( /*#__PURE__*/React.createElement(Input, {
        placeholder: intl.get('ciam.authority.model.authorityCustomer.dataName').d('客户企业名称')
      }))), /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator('dataCode')( /*#__PURE__*/React.createElement(Input, {
        placeholder: intl.get('ciam.authority.model.authorityCustomer.dataCode').d('客户企业代码')
      }))), /*#__PURE__*/React.createElement(FormItem, null, /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        onClick: function onClick() {
          return _this6.queryValue();
        },
        htmlType: "submit"
      }, intl.get('cpaas.common.button.search').d('查询'))), /*#__PURE__*/React.createElement(FormItem, null, /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        onClick: function onClick() {
          return _this6.dataSave();
        }
      }, intl.get('cpaas.common.button.save').d('保存'))));
    }
    /**
     *渲染事件
     *
     * @returns
     * @memberof Customer
     */

  }, {
    key: "render",
    value: function render() {
      var _this7 = this;

      var _this$props8 = this.props,
          _this$props8$authorit = _this$props8.authorityCustomer,
          _this$props8$authorit2 = _this$props8$authorit.data,
          data = _this$props8$authorit2 === void 0 ? {} : _this$props8$authorit2,
          _this$props8$authorit3 = _this$props8$authorit.head,
          head = _this$props8$authorit3 === void 0 ? {} : _this$props8$authorit3,
          loading = _this$props8.loading;
      var _this$state2 = this.state,
          selectedRows = _this$state2.selectedRows,
          newCreateRows = _this$state2.newCreateRows;
      var getFieldDecorator = this.props.form.getFieldDecorator;
      var dataSource = [].concat(_toConsumableArray(data.list), _toConsumableArray(newCreateRows));
      var columns = [{
        title: intl.get('ciam.authority.model.authorityCustomer.dataName').d('客户企业名称'),
        dataIndex: 'dataId',
        width: 150,
        render: function render(text, tableRecord) {
          return tableRecord.isEditing ? /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(tableRecord.authorityLineId, "#dataId"), {
            rules: [{
              required: true
            }]
          })( /*#__PURE__*/React.createElement(Lov, {
            code: "CIAM.USER_AUTHORITY_CUSTOMER",
            queryParams: {
              tenantId: 1
            },
            textValue: text,
            onChange: function onChange(_, record) {
              return _this7.setDataCode(record, tableRecord);
            }
          }))) : /*#__PURE__*/React.createElement("div", null, text);
        }
      }, {
        title: intl.get('ciam.authority.model.authorityCustomer.dataCode').d('客户企业代码'),
        dataIndex: 'dataCode',
        width: 100,
        render: function render(text, record) {
          return record.isEditing ? /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(record.authorityLineId, "#dataCode"), {
            initialValue: record.dataCode
          })( /*#__PURE__*/React.createElement(Input, {
            disabled: true
          }))) : /*#__PURE__*/React.createElement("div", null, text);
        }
      }, {
        title: intl.get('ciam.authority.model.authorityCustomer.dataName').d('客户企业名称'),
        dataIndex: 'dataName',
        width: 100,
        render: function render(text, record) {
          return record.isEditing ? /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(record.authorityLineId, "#dataName"), {
            initialValue: record.dataName
          })( /*#__PURE__*/React.createElement(Input, {
            disabled: true
          }))) : /*#__PURE__*/React.createElement("div", null, text);
        }
      }];
      var rowSelection = {
        selectedRowKeys: selectedRows.map(function (n) {
          return n.authorityLineId;
        }),
        onChange: this.handleSelectRows
      };

      var pagination = _objectSpread(_objectSpread({}, createPagination(data)), {}, {
        onShowSizeChange: function onShowSizeChange(_, size) {
          _this7.PageSize = size;
        }
      });

      return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
        className: "table-list-search"
      }, this.renderForm()), /*#__PURE__*/React.createElement("div", {
        style: {
          textAlign: 'right'
        }
      }, !head.includeAllFlag && /*#__PURE__*/React.createElement(Button, {
        style: {
          margin: '0 8px 16px 0'
        },
        onClick: function onClick() {
          return _this7.addData();
        }
      }), selectedRows.length > 0 && /*#__PURE__*/React.createElement(Button, {
        onClick: function onClick() {
          return _this7.remove();
        }
      }), /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'inline-block',
          margin: '0 8px 16px 0'
        }
      }, /*#__PURE__*/React.createElement("span", {
        style: {
          marginRight: '8px'
        }
      }, intl.get('ciam.authority.view.message.label').d('加入全部:')), /*#__PURE__*/React.createElement(Tooltip, {
        title: intl.get('ciam.authority.view.message.title.tooltip').d('“加入全部”即将所有客户权限自动添加至当前账户，无需再手工添加。'),
        placement: "right"
      }, /*#__PURE__*/React.createElement(Switch, {
        values: !!head.includeAllFlag,
        onChange: this.includeAllFlag
      })))), /*#__PURE__*/React.createElement(Table, {
        bordered: true,
        loading: loading,
        rowKey: "authorityLineId",
        dataSource: dataSource,
        pagination: pagination,
        columns: columns,
        scroll: {
          x: tableScrollWidth(columns)
        },
        rowSelection: head.includeAllFlag ? false : rowSelection,
        onChange: this.handleTableChange
      }));
    }
  }]);

  return Customer;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "addData", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "addData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "cancel", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "cancel"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "edit", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "edit"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSelectRows", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSelectRows"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "remove", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "remove"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "refresh", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "refresh"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "dataSave", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "dataSave"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "queryValue", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "queryValue"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "setDataCode", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "setDataCode"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "includeAllFlag", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "includeAllFlag"), _class2.prototype)), _class2)) || _class) || _class);
export { Customer as default };